import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { showToast, showLoadingToast, closeToast } from 'vant'

export const useAppStore = defineStore('app', () => {
  // 状态
  const loading = ref(false)
  const loadingText = ref('加载中...')
  const keepAliveComponents = ref([])
  const theme = ref('light') // light | dark
  const language = ref('zh-CN')
  const networkStatus = ref(navigator.onLine)
  const appConfig = ref({
    version: '1.0.0',
    apiBaseUrl: import.meta.env.VITE_API_BASE_URL || '/api',
    uploadUrl: import.meta.env.VITE_UPLOAD_URL || '/api/upload',
    staticUrl: import.meta.env.VITE_STATIC_URL || '/static'
  })
  
  // 设备信息
  const deviceInfo = ref({
    userAgent: navigator.userAgent,
    platform: navigator.platform,
    language: navigator.language,
    cookieEnabled: navigator.cookieEnabled,
    onLine: navigator.onLine,
    screenWidth: window.screen.width,
    screenHeight: window.screen.height,
    windowWidth: window.innerWidth,
    windowHeight: window.innerHeight
  })
  
  // 应用状态
  const appStatus = ref({
    isFirstVisit: true,
    lastActiveTime: Date.now(),
    visitCount: 0,
    errorCount: 0
  })

  // 计算属性
  const isDarkMode = computed(() => theme.value === 'dark')
  const isOnline = computed(() => networkStatus.value)
  const hasKeepAlive = computed(() => keepAliveComponents.value.length > 0)

  // 方法
  const setLoading = (status, text = '加载中...') => {
    loading.value = status
    loadingText.value = text
    
    if (status) {
      showLoadingToast({
        message: text,
        forbidClick: true,
        duration: 0
      })
    } else {
      closeToast()
    }
  }

  const setTheme = (newTheme) => {
    theme.value = newTheme
    document.documentElement.setAttribute('data-theme', newTheme)
    localStorage.setItem('app-theme', newTheme)
  }

  const setLanguage = (lang) => {
    language.value = lang
    localStorage.setItem('app-language', lang)
  }

  const addKeepAliveComponent = (componentName) => {
    if (!keepAliveComponents.value.includes(componentName)) {
      keepAliveComponents.value.push(componentName)
    }
  }

  const removeKeepAliveComponent = (componentName) => {
    const index = keepAliveComponents.value.indexOf(componentName)
    if (index > -1) {
      keepAliveComponents.value.splice(index, 1)
    }
  }

  const clearKeepAliveComponents = () => {
    keepAliveComponents.value = []
  }

  const updateNetworkStatus = (status) => {
    networkStatus.value = status
    
    if (status) {
      showToast('网络已连接')
    } else {
      showToast('网络连接已断开')
    }
  }

  const updateDeviceInfo = () => {
    deviceInfo.value = {
      ...deviceInfo.value,
      onLine: navigator.onLine,
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight
    }
  }

  const incrementErrorCount = () => {
    appStatus.value.errorCount++
  }

  const updateLastActiveTime = () => {
    appStatus.value.lastActiveTime = Date.now()
  }

  const incrementVisitCount = () => {
    appStatus.value.visitCount++
    appStatus.value.isFirstVisit = false
  }

  // 初始化应用
  const initApp = async () => {
    try {
      // 从本地存储恢复设置
      const savedTheme = localStorage.getItem('app-theme')
      if (savedTheme) {
        setTheme(savedTheme)
      } else {
        // 检测系统主题偏好
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
        setTheme(prefersDark ? 'dark' : 'light')
      }

      const savedLanguage = localStorage.getItem('app-language')
      if (savedLanguage) {
        setLanguage(savedLanguage)
      }

      // 恢复应用状态
      const savedAppStatus = localStorage.getItem('app-status')
      if (savedAppStatus) {
        const parsed = JSON.parse(savedAppStatus)
        appStatus.value = { ...appStatus.value, ...parsed }
      }

      // 更新设备信息
      updateDeviceInfo()

      // 监听网络状态变化
      window.addEventListener('online', () => updateNetworkStatus(true))
      window.addEventListener('offline', () => updateNetworkStatus(false))

      // 监听窗口大小变化
      window.addEventListener('resize', updateDeviceInfo)

      // 监听主题变化
      window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
        if (!localStorage.getItem('app-theme')) {
          setTheme(e.matches ? 'dark' : 'light')
        }
      })

      // 监听页面活动
      document.addEventListener('visibilitychange', () => {
        if (!document.hidden) {
          updateLastActiveTime()
        }
      })

      // 增加访问次数
      incrementVisitCount()

      console.log('应用初始化完成')
    } catch (error) {
      console.error('应用初始化失败:', error)
      incrementErrorCount()
    }
  }

  // 保存应用状态到本地存储
  const saveAppStatus = () => {
    try {
      localStorage.setItem('app-status', JSON.stringify(appStatus.value))
    } catch (error) {
      console.error('保存应用状态失败:', error)
    }
  }

  // 重置应用状态
  const resetApp = () => {
    loading.value = false
    loadingText.value = '加载中...'
    keepAliveComponents.value = []
    appStatus.value = {
      isFirstVisit: true,
      lastActiveTime: Date.now(),
      visitCount: 0,
      errorCount: 0
    }
    
    // 清除本地存储
    localStorage.removeItem('app-theme')
    localStorage.removeItem('app-language')
    localStorage.removeItem('app-status')
    
    // 重新初始化
    initApp()
  }

  // 获取应用统计信息
  const getAppStats = () => {
    return {
      ...appStatus.value,
      theme: theme.value,
      language: language.value,
      networkStatus: networkStatus.value,
      deviceInfo: deviceInfo.value,
      keepAliveCount: keepAliveComponents.value.length
    }
  }

  // 检查应用更新
  const checkForUpdates = async () => {
    try {
      // 这里可以调用API检查版本更新
      // const response = await api.checkVersion()
      // return response.data
      return { hasUpdate: false }
    } catch (error) {
      console.error('检查更新失败:', error)
      return { hasUpdate: false }
    }
  }

  // 监听页面卸载，保存状态
  window.addEventListener('beforeunload', saveAppStatus)

  return {
    // 状态
    loading,
    loadingText,
    keepAliveComponents,
    theme,
    language,
    networkStatus,
    appConfig,
    deviceInfo,
    appStatus,
    
    // 计算属性
    isDarkMode,
    isOnline,
    hasKeepAlive,
    
    // 方法
    setLoading,
    setTheme,
    setLanguage,
    addKeepAliveComponent,
    removeKeepAliveComponent,
    clearKeepAliveComponents,
    updateNetworkStatus,
    updateDeviceInfo,
    incrementErrorCount,
    updateLastActiveTime,
    incrementVisitCount,
    initApp,
    saveAppStatus,
    resetApp,
    getAppStats,
    checkForUpdates
  }
})